package cn.smile.commons.domain;

import cn.smile.commons.enums.base.TableOrderEnum;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.Data;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.io.Serial;
import java.io.Serializable;
import java.util.List;

/**
 * @author smile
 */
@Data
public abstract class BaseQueryEntity<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = -336442004849891159L;
    private static final String STRING_SPLIT_SYMBOL = ",";
    private static final String DEFAULT_FIELD = "createTime";

    /**
     * 分页参数页码
     */
    private Integer page = 1;

    /**
     * 分页参数条数
     */
    private Integer size = 10;

    /**
     * 排序字段
     */
    private String column;

    /**
     * 排序规则
     */
    private String order;

    public Page<T> queryPage() {
        Page<T> page = new Page<>(this.page, this.size);
        List<String> orderColumns = Lists.newArrayList();
        if (!ObjectUtils.isEmpty(column)) {
            List<String> split = Lists.newArrayList(column.split(STRING_SPLIT_SYMBOL));
            if (!CollectionUtils.isEmpty(split)) {
                for (String string : split) {
                    orderColumns.add(toField(string));
                }
            }
        } else {
            //默认创建时间倒序排列
            orderColumns.add(toField(DEFAULT_FIELD));
            order = TableOrderEnum.DESC.getCode();
        }
        if (TableOrderEnum.get(order) != TableOrderEnum.NULL && !CollectionUtils.isEmpty(orderColumns)) {
            List<OrderItem> items = Lists.newArrayList();
            for (String orderColumn : orderColumns) {
                OrderItem item = new OrderItem();
                if (TableOrderEnum.ASC == TableOrderEnum.get(order)) {
                    item.setAsc(Boolean.TRUE);
                } else if (TableOrderEnum.DESC == TableOrderEnum.get(order)) {
                    item.setAsc(Boolean.FALSE);
                }
                item.setColumn(orderColumn);
                items.add(item);
            }
            page.addOrder(items);
        }
        return page;
    }

    /**
     * 属性名转数据库字段 userName - user_name
     *
     * @param property 属性名
     * @return 转换结果
     */
    private static String toField(String property) {
        if (ObjectUtils.isEmpty(property)) {
            return "";
        }
        char[] chars = property.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : chars) {
            if (Character.isUpperCase(c)) {
                stringBuilder.append(String.format("_%s", Character.toLowerCase(c)));
            } else {
                stringBuilder.append(c);
            }
        }
        return stringBuilder.toString();
    }
}
